package fnord.network.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import fnord.illuminati.order.Order;
import fnord.network.OrderType;

public class ClientListenerThread extends Thread {
	
	private Socket _clientSocket;
	private Server _server;
	
	public ClientListenerThread(Socket client, Server server) {
		_clientSocket = client;
		_server = server;
	}

	public void run() {
		ObjectInputStream ois = null;
		if(!_clientSocket.isClosed()) {
			try {
				ois = new ObjectInputStream(_clientSocket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
		}
		while(!_clientSocket.isClosed()) {
			try {
				String s = (String) ois.readObject();
				OrderType ot = OrderType.getTypeFor(s);
				if(ot == OrderType.CHAT) {
					_server.sendChat((String)ois.readObject());
				}
				else if(ot.isOrder()) {
					_server.putOrder(this, (Order)ois.readObject());
				}
				else if(ot == OrderType.QUIT){
					//client is quitting...
					_server.quitClient(this);
					try {
						ois.close();
						_clientSocket.close();
					} catch(IOException e) {
						e.printStackTrace();
					}
				}
			} catch (IOException e) {
				try {
					ois.close();
					_clientSocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}		
				break;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Socket getSocket() {
		return _clientSocket;
	}
}
